<?php

require_once "./class/Object.class.php";

class Player extends Object {

	public $pseudo	= "";
	public $color   = "";
	public $game	= "";
	public $alive	= 0;
	public $message	= "";
	
	private $gameObject	= null;

	public function __construct( $identifier = null ) {

		parent::__construct( $identifier );
	
	}

	public function save() {
	
		$values	= array(
					"pseudo"	=> $this->pseudo,
					"color"     => $this->color,
					"game"		=> $this->game,
					"alive" 	=> $this->alive,
					"message"	=> $this->message,
				);
			
		return parent::save( $values );
	
	}
	
	public function getGameObject() {
	
		if ( $this->gameObject instanceof Game ) {
			return $this->gameObject;
		} else {
			$game	= new Game( $this->game );
			if ( $game->_identifier ) {
				$this->gameObject	= $game;
				return $game;
			} else {
				return null;
			}
		}
	
	}
	
	public function sendMessage( $message ) {
	
		$this->message	.= json_encode( $message ) . "\n";
		$this->save();
	
	}
	
	public function resetInactivityTimer() {
	
		$this->alive	= time();
		$this->save();
	
	}
	
	public function update() {
	
		$this->load( $this->_identifier );
		if ( $this->message != "" ) {
			return true;
		} else {
			return false;
		}
	
	}
		
	public function enterGame($pseudo, $color) {

        $game = $this->getGameObject();
		$this->pseudo = self::getNewPseudo( $pseudo, $game->_identifier );
		$this->color = $color;

		$x	= rand(0, 100);
		$y	= rand(0, 100);
		
		$message	= array(
						"message" => "newplayer",
						"params" => array(
							"id" => $this->_identifier,
							"nickname" => $this->pseudo,
							"color" => $this->color,
							"x" => $x,
							"y" => $y,
						),
					);

		$game->sendMessage( $message );
		$game->addNewPlayer();
	    
	}
	public function waitUntilNewMessageArrives() {
	
		// check if the data file has been modified
		while( !$this->update() ) {
			usleep(10000);	// sleep 10ms to unload the CPU
		}
		
		return true;

	}
	
	public function popMessage() {
	
		$messages	= explode("\n",trim($this->message));
		if (count($messages)) {
			$message	= array_shift( $messages );
			if ( count( $messages ) ) {
				$this->message	= implode( "\n", $messages );
			} else {
				$this->message	= "";
			}
			$this->save();
			return "{ok}".$message;
		}
		return "";
	
	}

	public static function cleanUp() {
	
		$aliveMaxTime	= time() - TIME_BEFORE_DEATH;
		$conn	= new DB();
	
		// Recherche des utilisateurs perdus :
		$query	= "SELECT _identifier as player, game FROM player WHERE "
				. "`alive` < '$aliveMaxTime'";
		$conn->query( $query );
		if ( $conn->count() > 0 ) {
			while( $player = $conn->fetch() ) {
				Game::sendDeadPlayerMessage( $player );
			}
		}		

		$query	= "DELETE FROM player WHERE "
				. "`alive` < $aliveMaxTime";
		$conn->query( $query );
	
	}
	
	public static function getNewPseudo( $pseudo, $game ) {
	
		if ( $pseudo == "" ) {
			$pseudo	= "unknown";
		}
		
		$conn	= new DB();
		$query	= "SELECT _identifier FROM player WHERE "
				. "game = $game AND pseudo = '$pseudo'";
		$conn->query( $query );
		$i		= 0;
		while( $conn->count() ) {
			$i++;
			$query	= "SELECT _identifier FROM player WHERE "
					. "game = $game AND pseudo = '" . $pseudo . "-" . $i . "'";
			$conn->query( $query );
		}
		if ( $i > 0 ) {
			$pseudo	.= "-" . $i;
		}
		
		return $pseudo;
	
	}
	
	public static function getNewPlayer( ) {

		/*  getNewPlayer est appelée par le client pour s'enregistrer dans le jeu
		    Elle prend en paramètre le nom que le client souhaiterait avoir
		    En cas de succès, elle fait deux choses :
		        - envoyer à l'appelant son id unique
		        - envoyer a tous les joueurs (y compris l'appelant) un message "newplayer"
		*/
	
		$theGame	= Game::getAvailableGame();
		
		$player	= new Player();
		$player->game	= $theGame->_identifier;
		$player->alive	= time();
		$player->save();

		$message	= array(
						"message" => "newid",
						"params" => array(
							"id" => $player->_identifier,
						),
					);
		
		$player->sendMessage( $message );
		
		return $player->_identifier;		
				
	}

}

?>